package util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Auther: songjc
 * @Date: 2020/12/17 16:16
 * @Description:java实现文件压缩并下载
 */
public class DownloadFileToZip {
        public static HttpServletResponse downLoadFiles(List<File> files, HttpServletRequest request, HttpServletResponse response) throws Exception {
            try {
                new File(request.getSession().getServletContext().getRealPath("/qrcode.zip"));
                String path=Thread.currentThread().getContextClassLoader().getResource("").getPath()+ "word/yzyzzmb" + ".zip";
                File file = new File(path);
                if (!file.exists()){
                    file.createNewFile();
                }
                //创建文件输出流
                FileOutputStream fous = new FileOutputStream(file);
                /**打包的方法我们会用到ZipOutputStream这样一个输出流,
                 * 所以这里我们把输出流转换一下*/
                //            org.apache.tools.zip.ZipOutputStream zipOut
                //                = new org.apache.tools.zip.ZipOutputStream(fous);
                ZipOutputStream zipOut
                        = new ZipOutputStream(fous);
                /**这个方法接受的就是一个所要打包文件的集合，
                 * 还有一个ZipOutputStream
                 */
                zipFile(files, zipOut);
                zipOut.close();
                fous.close();
                //   FileUtil.downloadFile(response,path);
                return downloadZip(file,response);
            }catch (Exception e) {
                e.printStackTrace();
            }
            /**直到文件的打包已经成功了，
             * 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中，
             * 稍后会呈现出来，接下来的就是往客户端写数据了
             */
            // OutputStream out = response.getOutputStream();
            return response ;
        }


        public static void zipFile
                (List files,ZipOutputStream outputStream) {
            int size = files.size();
            for(int i = 0; i < size; i++) {
                File file = (File) files.get(i);
                zipFile(file, outputStream);
            }
        }

        public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }finally{
                try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
        }


        public static void zipFile(File inputFile,
                                   ZipOutputStream ouputStream) {
            try {
                if(inputFile.exists()) {
                    if (inputFile.isFile()) {
                        FileInputStream IN = new FileInputStream(inputFile);
                        BufferedInputStream bins = new BufferedInputStream(IN, 512);
                        //org.apache.tools.zip.ZipEntry
                        ZipEntry entry = new ZipEntry(inputFile.getName());
                        ouputStream.putNextEntry(entry);
                        // 向压缩文件中输出数据
                        int nNumber;
                        byte[] buffer = new byte[512];
                        while ((nNumber = bins.read(buffer)) != -1) {
                            ouputStream.write(buffer, 0, nNumber);
                        }
                        // 关闭创建的流对象
                        bins.close();
                        IN.close();
                    } else {
                        try {
                            File[] files = inputFile.listFiles();
                            for (int i = 0; i < files.length; i++) {
                                zipFile(files[i], ouputStream);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        /**
         * zip文件压缩
         * @param inputFile 待压缩文件夹/文件名
         * @param outputFile 生成的压缩包名字
         */

        public static void ZipCompress(String inputFile, String outputFile) throws Exception {
            //创建zip输出流
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
            //创建缓冲输出流
            BufferedOutputStream bos = new BufferedOutputStream(out);
            File input = new File(inputFile);
            compress(out, bos, input,null);
            bos.close();
            out.close();
        }

        //递归压缩
        public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException {
            if (name == null) {
                name = input.getName();
            }
            //如果路径为目录（文件夹）
            if (input.isDirectory()) {
                //取出文件夹中的文件（或子文件夹）
                File[] flist = input.listFiles();

                if (flist.length == 0)//如果文件夹为空，则只需在目的地zip文件中写入一个目录进入
                {
                    out.putNextEntry(new ZipEntry(name + "/"));
                } else//如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
                {
                    for (int i = 0; i < flist.length; i++) {
                        compress(out, bos, flist[i], name + "/" + flist[i].getName());
                    }
                }
            } else//如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
            {
                out.putNextEntry(new ZipEntry(name));
                FileInputStream fos = new FileInputStream(input);
                BufferedInputStream bis = new BufferedInputStream(fos);
                int len = -1;
                //将源文件写入到zip文件中
                byte[] buf = new byte[1024];
                while ((len = bis.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                bis.close();
                fos.close();
            }
        }
}
